package com.tiza.xiaoyoubao.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.BrowseTaskOrderInfo;
import com.tiza.xiaoyoubao.entity.InsertTaskInfo;
import com.tiza.xiaoyoubao.entity.TaoBaoAccountInfo;
import com.tiza.xiaoyoubao.entity.TaskOrderInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static com.tiza.xiaoyoubao.R.id.tv_orderNum;
import static com.tiza.xiaoyoubao.R.id.tv_userId;

/**
 * Created by mapple on 17/4/11.
 * 浏览任务 手机淘宝  接任务
 */



//{
//        "Message":"查询成功",
//        "Code":0,
//        "Data":[
//        {
//        "baseCmi":"1.50",
//        "addTime":null,
//        "keywords":"1",
//        "orderScann":"1",
//        "settingTime":"0",
//        "number":"0",
//        "url3":"",
//        "sellerId":null,
//        "taskCode":"53509710",
//        "url2":"",
//        "price":"1",
//        "mobilePrice":"1",
//        "id":1,
//        "singleMulti":"单商品",
//        "price3":"",
//        "price2":"",
//        "images":"/uploads/201708/21/1503321530.jpg",
//        "dayOrder":"0",
//        "pnumber":"0.00",
//        "scannSetting":"{c_shop=1, c_good=1, store_number=5, c_add_good=1}",
//        "minPrice":"",
//        "orders":"10",
//        "maxPrice":"",
//        "shopID":5,
//        "startDate":"",
//        "images2Thumb":"",
//        "imagesThumb":"/uploads/201708/21/1503321530_thumb.jpg",
//        "city":"全国",
//        "number3":"0",
//        "typeName":"手机淘宝浏览任务",
//        "shopName":"小优宝旗舰店2",
//        "number2":"0",
//        "title":"棒球服女春秋季短款2017新款百搭毛衣外套女宽松韩版大码针织开衫",
//        "images3":"",
//        "images2":"",
//        "receiving":"1",
//        "typePid":"002",
//        "orderid":null,
//        "message":"",
//        "userId":"6002",
//        "url":"https://detail.tmall.com/item.htm?id=555572118964&ali_refid=a3_430583_1006:1150351805:N:%E7%A7%8B%E5%AD%A3%E5%A4%96%E5%A5%97%E5%A5%B3%E5%AD%A6%E7%94%9F:482537404523ad456b51c253dea11169&ali_trackid=1_482537404523ad456b51c253dea11169&spm=a230r.1.14.1.ebb2eb2jL7u7i",
//        "images3Thumb":"",
//        "endHour":"",
//        "startHour":"",
//        "orderFlag":null,
//        "priceSection":"0-100",
//        "backName":"平台返款",
//        "location":"xiaoliang",
//        "endTime":null,
//        "taskNumber":"10",
//        "account":null,
//        "remarks":""
//        },
//        ]
//        }

public class BrowseMpTaoBaoTaskDetialFragment extends BaseFragment {
    @BindView(R.id.lv_listView)
    ListView lv_listView;
    @BindView(R.id.tv_keyWord)
    TextView tv_keyWord;
    @BindView(R.id.tv_taskId)
    TextView tv_taskId;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_goodsType)
    TextView tv_goodsType;
    @BindView(R.id.tv_additionalRequest)
    TextView tv_additionalRequest;
    private BrowseTaskOrderInfo mOrderInfo;
    @BindView(R.id.view_bindingTaoBao)
    View view_bindingTaoBao;
    DateFormat df;
    Date date;
    long startTime, endTime;
    private List<TaoBaoAccountInfo> mList = new ArrayList<>();
    private List<TaoBaoAccountInfo> mList2 = new ArrayList<>();
    private BrowseTaoBaoInfoAdapter mBrowseTaoBaoInfoAdapter = new BrowseTaoBaoInfoAdapter();
    private String account;
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_browse_mp_taobao_detial;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                Bundle args = getArguments();
                mOrderInfo = (BrowseTaskOrderInfo) args.getSerializable("info");
                if (null == mOrderInfo) {
                    toast("详情加载失败");
                    finish();
                }
    }

    @Override
    protected void initData() {
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    protected void initView() {
        getBankTaoBao();
        tv_taskId.setText("ID:" + mOrderInfo.getUserId());
        tv_money.setText(DateUtils.formateRate(mOrderInfo.getBaseCmi()));
        tv_goodsType.setText(mOrderInfo.getSingleMulti());
        if (TextUtils.isEmpty(mOrderInfo.getKeywords())) {
            tv_keyWord.setText("无");
        } else {
            tv_keyWord.setText(mOrderInfo.getKeywords());
        }
        if (mOrderInfo.getRemarks().equals(" ")) {
            tv_additionalRequest.setText("此商家无其他要求");
        } else {
            tv_additionalRequest.setText(mOrderInfo.getRemarks());
        }
        lv_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                if (mList2.get(i).getNumber()==0) {
                    toast("今日可接单数已达上线");
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("提示");
                    String message = "确认使用" + mList2.get(i)
                            .getAccount() + "接任务吗?\n接单2小时内必须完成任务操作,否则将扣除1金," +
                            "如果5分钟内取消不扣金";
                    builder.setMessage(message);
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                date = df.parse(df.format(new Date()));
                                startTime = date.getTime() / 1000;
                                //endTime = startTime + 7200;
                                endTime = startTime + 3600;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            account = mList2.get(i).getAccount();
                            insertTask();
                            // 隐藏当前对话框
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 隐藏当前对话框
                            toast("取消");
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            }

        });
    }
    @OnClick({R.id.view_bindingTaoBao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_bindingTaoBao:
                UIHelper.showAccountBinding(mActivity);
                finish();
                break;
            default:
                break;
        }
    }

    private void insertTask() {
        ApiHttpClient.insertTask(this,
                String.valueOf(mOrderInfo.getId()), mOrderInfo.getTaskCode(),
                mOrderInfo.getUserId(), account,
                userInfo.getWebzzCmsBuyerInfo().getUserid(),
                String.valueOf(startTime), String.valueOf(endTime), "002",
                String.valueOf(mOrderInfo.getShopID()),
                new JsonCallback<InsertTaskInfo>(InsertTaskInfo.class) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("接单失败");
                    }

                    @Override
                    public void onResponse(ResponseInfo<InsertTaskInfo> response) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        List<InsertTaskInfo> data = response.getData();
                        if (null == data || data.size() == 0) {
                            toast("接单失败");
                            return;
                        }
                        InsertTaskInfo insertTaskInfo = data.get(0);
                        Hawk.put(Constants.KEY_INSERTTASK_INFO, insertTaskInfo);
                        UIHelper.showBrowseAttention(mActivity);
                        finish();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    private void getBankTaoBao() {
        ApiHttpClient.getBuyerTaobaoTow(this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                new JsonCallback<TaoBaoAccountInfo>(TaoBaoAccountInfo.class) {
                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("网络异常,请稍后重试");
                    }

                    @Override
                    public void onResponse(
                            ResponseInfo<TaoBaoAccountInfo> response
                    ) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        mList = response.getData();
                        if (null == mList || mList.size() == 0) {
                            view_bindingTaoBao.setVisibility(View.VISIBLE);
                        } else {
                            for (int i = 0; i < mList.size(); i++) {
                                if (mList.get(i).getAuth() == 1) {
                                    mList2.add(mList.get(i));
                                }
                            }
                        }
                        if (mList2.size() == 0) {
                            view_bindingTaoBao.setVisibility(View.VISIBLE);
                        } else {
                            lv_listView.setAdapter(mBrowseTaoBaoInfoAdapter);
                        }
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    class BrowseTaoBaoInfoAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList2.size();
        }

        @Override
        public Object getItem(int position) {
            return mList2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.item_taobao_info, null);
                holder = new ViewHolder();
                holder.tv_userId = (TextView) convertView.findViewById(tv_userId);
                holder.tv_orderNum = (TextView) convertView.findViewById(tv_orderNum);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_userId.setText(mList2.get(position).getAccount());
            holder.tv_orderNum.setText("(今日可接单" + mList2.get(position).getNumber() + "笔)");
            return convertView;
        }
    }

    static class ViewHolder {
        public TextView tv_userId;
        public TextView tv_orderNum;
    }
}
